package com.yylending.las.repay;

import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.airbnb.lottie.LottieAnimationView;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yylending.las.Constants;
import com.yylending.las.R;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.common.utils.TimeUtils;
import com.yylending.las.common.widgets.CircleLoading;
import com.yylending.las.common.widgets.TelephoneTextView;
import com.yylending.las.main.MainActivity;

import java.util.List;

/**
 * 还款页面
 * Created by laixj on 2017/5/25.
 * Copyright ©2016 www.yylending.com. All Rights Reserved.
 */

public class RepaymentFragment extends BaseFragment implements LoanDetailPresenter.View, View.OnClickListener {

	static final String TAG = RepaymentFragment.class.getSimpleName();

	//    static final int LOADER_ID_MY_LENDING = 1;
	// 还款逾期
	private static final int REPAY_OVERDUE = 1;
	// 正在还款中
	private static final int IS_DOING_REPAY = 2;

	@BindView(R.id.title_left_iv)
	ImageView mTitleLeftIv;
	@BindView(R.id.title_tv)
	TextView mTitleTv;
	@BindView(R.id.title_right_tv)
	TextView mTitleRightTv;
	@BindView(R.id.title_right_iv)
	ImageView mTitleRightIv;
	@BindView(R.id.layout_title_bar)
	RelativeLayout mLayoutTitleBar;
	@BindView(R.id.top_tips_tv)
	TextView mTopTipsTv;
	@BindView(R.id.circle_loading)
	CircleLoading mCircleLoading;
	@BindView(R.id.repayment_money_hint_tv)
	TextView mRepaymentMoneyHintTv;
	@BindView(R.id.repayment_money_tv)
	TextView mRepaymentMoneyTv;
	@BindView(R.id.repayment_overdue_tv)
	TextView mRepaymentOverdueTv;
	@BindView(R.id.repay_status_rl)
	RelativeLayout mRepayStatusRl;
	@BindView(R.id.repayment_day_tv)
	TextView mRepaymentDayTv;
	@BindView(R.id.repay_date_rl)
	RelativeLayout mRepayDateRl;
	@BindView(R.id.divider_view1)
	View mDividerView1;
	@BindView(R.id.repayment_term_tv)
	TextView mRepaymentTermTv;
	@BindView(R.id.repay_period_rl)
	RelativeLayout mRepayPeriodRl;
	@BindView(R.id.divider_view2)
	View mDividerView2;
	@BindView(R.id.repayment_bank_card_tv)
	TextView mRepaymentBankTv;
	@BindView(R.id.repayment_service_tv)
	TelephoneTextView mRepaymentServiceTv;
	@BindView(R.id.has_loan_rl)
	RelativeLayout mHasLoanRl;
	@BindView(R.id.no_repay_ll)
	LinearLayout mNoRepayLl;
	@BindView(R.id.repay_bank_card_rl)
	RelativeLayout mRepayBankCardRl;

    private View mNoNetWorkRl;
    private LottieAnimationView mLoadingView;
	private View mPageLoadingLl;
    private View mLoadStatusView;
    Unbinder mUnbind;
    private LoanDetailPresenter mLoanDetailPresenter;

	public static BaseFragment newInstance() {
		BaseFragment fragment = new RepaymentFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_repayment, container, false);
        mUnbind = ButterKnife.bind(this, rootView);
        mNoNetWorkRl = rootView.findViewById(R.id.no_network_layout);
        mLoadingView = (LottieAnimationView)rootView.findViewById(R.id.loading_view);
		mPageLoadingLl = rootView.findViewById(R.id.page_loading_ll);
        mLoadStatusView = rootView.findViewById(R.id.load_status_fl);
        mNoNetWorkRl.setOnClickListener(this);
        initView();
        return rootView;
    }

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		CLog.i(TAG, "还款页 onViewCreated");
		getLoaderManager().initLoader(MainActivity.LOADER_ID_MY_LENDING, null, this);
	}

	private void initView() {
		mTitleLeftIv.setVisibility(View.GONE);
		mTitleRightIv.setVisibility(View.GONE);
		mTitleRightTv.setText(R.string.repay_detail);
		mTitleTv.setText(R.string.tab_repay);

		mRepaymentServiceTv.setPageNo(Constants.PAGE_NO_MAIN_ACTIVITY);
	}

    @Override
    public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
        switch (loader.getId()) {
            case MainActivity.LOADER_ID_MY_LENDING:
                mLoanDetailPresenter = (LoanDetailPresenter) data;
                mLoanDetailPresenter.attach(this);
				mPageLoadingLl.setVisibility(View.VISIBLE);
                mLoadStatusView.setVisibility(View.VISIBLE);
                mLoadingView.playAnimation();
                mNoNetWorkRl.setVisibility(View.GONE);
                mLoanDetailPresenter.getLoanDetail("", "", false);
                break;
        }
    }

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case MainActivity.LOADER_ID_MY_LENDING:
				return new PresenterLoader<>(getActivity(), new LoanDetailPresenter.Generator());
			default:
				return null;
		}
	}

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbind.unbind();
        getLoaderManager().destroyLoader(MainActivity.LOADER_ID_MY_LENDING);
        mLoadingView.cancelAnimation();
        mLoadingView.clearAnimation();
    }

    @Override
    public void getLoanDetailSuccess(List<LoanDetailModel.LoanDetail> result) {
        mNoNetWorkRl.setVisibility(View.GONE);
		mPageLoadingLl.setVisibility(View.GONE);
        mLoadStatusView.setVisibility(View.GONE);
       // refreshData(result);
    }

	private void refreshData(LoanDetailModel.LoanDetail result) {
		mCircleLoading.setVisibility(View.VISIBLE);
		mRepayDateRl.setVisibility(View.VISIBLE);
		mDividerView1.setVisibility(View.VISIBLE);
		mRepayPeriodRl.setVisibility(View.VISIBLE);
		mDividerView2.setVisibility(View.VISIBLE);
		mRepayBankCardRl.setVisibility(View.VISIBLE);
		mRepaymentServiceTv.setVisibility(View.VISIBLE);
		((MainActivity)getActivity()).mRepayStatus=result.repayStatus;
		if (!TextUtils.equals(LoanDetailPresenter.REPAY_STATUS_NO_DATA, result.repayStatus)
				&& !TextUtils.equals(LoanDetailPresenter.REPAY_STATUS_NO_LOAN, result.repayStatus)) {
			int totalTerms = Integer.valueOf(result.loanTerm);
			int leftTerms = Integer.valueOf(result.repayTerm);
			mCircleLoading.setAnimationDelay(10);//动画延时
			mCircleLoading.setPieceCount(totalTerms);//圆被分隔成多少份
			mCircleLoading.setEndPiece(totalTerms - leftTerms);//已还期数
		}

		mTopTipsTv.setVisibility(View.GONE);
		mHasLoanRl.setVisibility(View.VISIBLE);
		mNoRepayLl.setVisibility(View.GONE);
		mTitleRightTv.setVisibility(View.VISIBLE);

		switch (result.repayStatus) {
			case LoanDetailPresenter.REPAY_STATUS_NO_DATA:
			case LoanDetailPresenter.REPAY_STATUS_NO_LOAN: // 无借款
				mHasLoanRl.setVisibility(View.GONE);
				mNoRepayLl.setVisibility(View.VISIBLE);
				mTitleRightTv.setVisibility(View.GONE);
				break;
			case LoanDetailPresenter.REPAY_STATUS_PAY_OFF: // 已还清, 原型没有该状态, 后台接口有返回.

				break;
			case LoanDetailPresenter.REPAY_STATUS_HAS_PAY: // 本期已还
				mRepaymentOverdueTv.setVisibility(View.VISIBLE);
				mRepaymentMoneyTv.setVisibility(View.GONE);
				mRepaymentMoneyHintTv.setVisibility(View.GONE);
				mRepaymentOverdueTv.setTextColor(getResources().getColor(R.color.color_569afc));
				mRepaymentOverdueTv.setText(R.string.money_has_repay_of_this_term);
				break;
			case LoanDetailPresenter.REPAY_STATUS_OVERDUE: // 本期逾期
				mRepaymentOverdueTv.setVisibility(View.VISIBLE);
				mRepaymentMoneyTv.setVisibility(View.GONE);
				mRepaymentMoneyHintTv.setVisibility(View.GONE);
				mRepaymentOverdueTv.setTextColor(getResources().getColor(R.color.color_fff44d19));
				mRepaymentOverdueTv.setText(R.string.be_overdue);
				// 这行代码仅在已逾期时展示.
				mCircleLoading.showCircleOnly(true, getContext().getResources().getColor(R.color.color_f9e1de));
				generateTopTipsStatus(REPAY_OVERDUE);
				break;
			case LoanDetailPresenter.REPAY_STATUS_REPAY_PROCESSING: // 还款处理中
				mRepaymentOverdueTv.setVisibility(View.GONE);
				mRepaymentMoneyTv.setVisibility(View.VISIBLE);
				mRepaymentMoneyHintTv.setVisibility(View.VISIBLE);
				mRepaymentMoneyTv.setText(String.format(getString(R.string.apply_quota_num), FormatUtils.getAmountWithSymbol(result.repayAmount)));
				generateTopTipsStatus(IS_DOING_REPAY);
				break;
			case LoanDetailPresenter.REPAY_STATUS_TO_REPAY: // 本期待还
				mRepaymentOverdueTv.setVisibility(View.GONE);
				mRepaymentMoneyTv.setVisibility(View.VISIBLE);
				mRepaymentMoneyHintTv.setVisibility(View.VISIBLE);
				mRepaymentMoneyTv.setText(String.format(getString(R.string.apply_quota_num), FormatUtils.getAmountWithSymbol(result.repayAmount)));
				break;
			default:
				break;
		}

		long repayDate = TextUtils.isEmpty(result.repayDate) ? 0 : Long.valueOf(result.repayDate);//sometimes, repayDate == null
		mRepaymentDayTv.setText(TimeUtils.formatDateTimeMonthSingleZh(repayDate));
		mRepaymentTermTv.setText(String.format(getString(R.string.left_pay_term), result.repayTerm));
		mRepaymentBankTv.setText(String.format(getString(R.string.repay_bank_card), result.repayBank, result.repayCard));
	}

    @Override
    public void getLoanDetailFailed(String msg) {
        mLoadStatusView.setVisibility(View.VISIBLE);
        mNoNetWorkRl.setVisibility(View.VISIBLE);
		mPageLoadingLl.setVisibility(View.GONE);
    }

    @Override
    public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
        super.onFunctionalError(e, autoTips, functionalCode);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mLoadStatusView.setVisibility(View.VISIBLE);
                mNoNetWorkRl.setVisibility(View.VISIBLE);
				mPageLoadingLl.setVisibility(View.GONE);
            }
        });
    }

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
	}

	@OnClick({R.id.title_right_tv})
	public void onBtnClick(View v) {
		switch (v.getId()) {
			case R.id.title_right_tv:
				//RepayDetailActivity.start(getActivity(), "");
				break;
			default:
				break;
		}
	}

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.no_network_layout:
                mLoanDetailPresenter.getLoanDetail("", "", false);
                mNoNetWorkRl.setVisibility(View.GONE);
				mPageLoadingLl.setVisibility(View.VISIBLE);
                mLoadStatusView.setVisibility(View.VISIBLE);
                mLoadingView.playAnimation();
                break;
            default:
                break;
        }
    }

	private void generateTopTipsStatus(int status) {
		GradientDrawable drawable = (GradientDrawable) mTopTipsTv.getBackground();

		switch (status) {
			case REPAY_OVERDUE:
				mTopTipsTv.setVisibility(View.VISIBLE);
				mTopTipsTv.setTextColor(getResources().getColor(R.color.color_fff44d19));
				mTopTipsTv.setText(R.string.repay_overdue_tips);
				drawable.setColor(getResources().getColor(R.color.color_f9e1de));
				break;
			case IS_DOING_REPAY:
				mTopTipsTv.setVisibility(View.VISIBLE);
				mTopTipsTv.setText(R.string.is_repaying_tips);
				mTopTipsTv.setTextColor(getResources().getColor(R.color.color_5c8eff));
				drawable.setColor(getResources().getColor(R.color.color_cae5ff));
				break;
			default:
				break;
		}
	}
}